// utils/menu.ts
import type { MenuItem } from '@/types/role'

/**
 * 构建菜单树形结构
 */
export function buildMenuTree(menus: MenuItem[]): MenuItem[] {
  const menuMap = new Map<number, MenuItem>()
  const tree: MenuItem[] = []
  
  // 创建映射
  menus.forEach(menu => {
    menuMap.set(menu.id, { ...menu, children: [] })
  })
  
  // 构建树形结构
  menus.forEach(menu => {
    const node = menuMap.get(menu.id)!
    if (menu.pid === 0) {
      tree.push(node)
    } else {
      const parent = menuMap.get(menu.pid)
      if (parent) {
        parent.children!.push(node)
      }
    }
  })
  
  // 排序
  const sortTree = (nodes: MenuItem[]) => {
    nodes.sort((a, b) => (a.sort || 0) - (b.sort || 0))
    nodes.forEach(node => {
      if (node.children && node.children.length > 0) {
        sortTree(node.children)
      }
    })
  }
  
  sortTree(tree)
  return tree
}

/**
 * 获取所有选中的菜单ID（包括半选中的父级菜单）
 */
export function getAllCheckedMenuKeys(treeRef: any): number[] {
  const checkedKeys = treeRef.getCheckedKeys()
  const halfCheckedKeys = treeRef.getHalfCheckedKeys()
  return [...checkedKeys, ...halfCheckedKeys]
}